package com.breezelin.freshmarket.fragments;

/**
 * Created by Breeze Lin
 * 2016/5/18 22:58
 * 1linyufeng1@gmail.com
 */

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.breezelin.freshmarket.R;
import com.breezelin.freshmarket.activities.CategoryActivity;
import com.breezelin.freshmarket.adpaters.CategoryAdapter;
import com.breezelin.freshmarket.app.BaseFragment;
import com.breezelin.freshmarket.entities.data.Category;
import com.breezelin.freshmarket.entities.rsp.CategoriesRsp;
import com.breezelin.freshmarket.network.TaskCanceler;
import com.breezelin.freshmarket.network.asynctasks.AllCategoryTask;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 * <p/>
 * 分类页面
 */
public class CategoryFragment extends BaseFragment implements CategoryAdapter.CategoryListener, SwipeRefreshLayout.OnRefreshListener {

	/**
	 * 刷新布局
	 */
	private SwipeRefreshLayout refreshLayout;
	/**
	 * 目录集合
	 */
	private ArrayList<Category> categories;
	/**
	 * 适配器
	 */
	private CategoryAdapter adapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
	                         Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_category, container, false);

		bindViews();
		loadContents();

		return rootView;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		TaskCanceler.cancelCategoryRequests();
	}

	/**
	 * 绑定视图
	 */
	private void bindViews() {
		// 基础视图设置
		refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.layout_refresh);
		refreshLayout.setEnabled(true);
		refreshLayout.setOnRefreshListener(this);
		ListView list = (ListView) rootView.findViewById(R.id.list);
		categories = new ArrayList<>();
		adapter = new CategoryAdapter(getActivity(), categories, this);
		list.setAdapter(adapter);
	}

	/**
	 * 加载内容
	 */
	private void loadContents() {
		new AllCategoryTask() {
			@Override
			protected void onSuccess(CategoriesRsp categoriesRsp) {
				categories.clear();
				categories.addAll(categoriesRsp.getCategories());
				adapter.notifyDataSetChanged();
				if (refreshLayout.isRefreshing()) {
					refreshLayout.setRefreshing(false);
					showToast(R.string.toast_page_loaded);
				}
			}
		}.execute();
	}

	@Override
	public void onCategorySelected(Category category) {
		Intent intent = new Intent(getActivity(), CategoryActivity.class);
		intent.putExtra("category", category);
		startActivity(intent);
	}

	@Override
	public void onRefresh() {
		loadContents();
	}
}
